import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './ProjectsPage.css';
import CreateProjectGroupModal from '../modals/CreateProjectGroupModal';
import CreateProjectModal from '../modals/CreateProjectModal';
import { projectApi, projectGroupApi } from '../../services/api';

const ProjectsPage = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [projects, setProjects] = useState([]);
  const [total, setTotal] = useState(0);

  // 搜索状态
  const [projectGroupId, setProjectGroupId] = useState('');
  const [projectIdSearch, setProjectIdSearch] = useState('');
  
  // 分页状态
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(10);
  
  // 项目组数据
  const [projectGroups, setProjectGroups] = useState([]);
  
  // 弹框状态
  const [isProjectGroupModalOpen, setIsProjectGroupModalOpen] = useState(false);
  const [isProjectModalOpen, setIsProjectModalOpen] = useState(false);

  // 加载项目组数据
  const loadProjectGroups = async () => {
    try {
      const response = await projectGroupApi.getProjectGroups(1, 100); // 获取足够多的项目组数据
      if (response.code === 200 && response.data) {
        setProjectGroups(response.data.records || []);
        console.log('加载项目组成功:', response.data.records);
      } else {
        console.error('加载项目组失败:', response.message);
      }
    } catch (error) {
      console.error('加载项目组异常:', error);
    }
  };

  // 加载项目数据
  const loadProjects = async () => {
    try {
      setLoading(true);
      const response = await projectApi.getProjects(page, size, projectIdSearch, projectGroupId);
      if (response.code === 200 && response.data) {
        setProjects(response.data.records || []);
        setTotal(response.data.total || 0);
        console.log('加载项目成功:', response.data.records);
      } else {
        console.error('加载项目失败:', response.message);
      }
    } catch (error) {
      console.error('加载项目异常:', error);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadProjectGroups();
  }, []);
  
  // 当搜索条件或分页变化时加载项目数据
  useEffect(() => {
    loadProjects();
  }, [page, size, projectGroupId, projectIdSearch]);

  // 处理搜索
  const handleSearch = () => {
    // 调用API进行搜索
    console.log('搜索项目组ID:', projectGroupId);
    console.log('搜索项目ID:', projectIdSearch);
    // 重置页码，加载数据会通过 useEffect 触发
    setPage(1);
  };
  
  // 处理创建项目组
  const handleCreateProjectGroup = async (projectGroup) => {
    try {
      console.log('创建项目组:', projectGroup);
      const response = await projectGroupApi.addProjectGroup(projectGroup);
      if (response.code === 200 && response.data) {
        alert('创建项目组成功');
        setIsProjectGroupModalOpen(false);
        loadProjectGroups();
      } else {
        alert(`创建项目组失败: ${response.message}`);
      }
    } catch (error) {
      console.error('创建项目组异常:', error);
      alert(`创建项目组异常: ${error.message}`);
    }
  };
  
  // 处理创建项目
  const handleCreateProject = async (project) => {
    try {
      const response = await projectApi.addProject(project);
      if (response.code === 200 && response.data) {
        // alert('创建项目成功');
        setIsProjectModalOpen(false);
        loadProjects(); // 创建成功后刷新项目列表
      } else {
        alert(`创建项目失败: ${response.message}`);
      }
    } catch (error) {
      console.error('创建项目异常:', error);
      alert(`创建项目异常: ${error.message}`);
    }
  };
  
  // 处理新增版本
  const handleAddVersion = (e, project) => {
    e.preventDefault();
    e.stopPropagation();
    console.log('跳转到新增版本页面，项目ID:', project.id);
    // 使用 React Router 的 navigate 函数进行路由跳转，保持单页应用状态
    navigate(`/project/${project.id}/add-version`);
  };

  return (
    <div className="projects-page">
      <div className="search-bar">
        <div className="search-item">
          <label>项目组：</label>
          <select 
            value={projectGroupId}
            onChange={(e) => setProjectGroupId(e.target.value)}
            className="project-group-select"
          >
            <option value="">请选择项目组</option>
            {projectGroups.map(group => (
              <option key={group.id} value={group.id}>{group.name}</option>
            ))}
          </select>
        </div>
        <div className="search-item">
          <label>项目：</label>
          <input 
            type="text" 
            value={projectIdSearch}
            onChange={(e) => setProjectIdSearch(e.target.value)}
            placeholder="请输入"
          />
        </div>
        <div className="search-actions">
          <button className="btn-search" onClick={handleSearch}>查 询</button>
          <button className="btn-reset" onClick={() => {
            setProjectGroupId('');
            setProjectIdSearch('');
          }}>重 置</button>
        </div>
        <div className="action-buttons">
          <button className="btn-create" onClick={() => setIsProjectModalOpen(true)}>
            <span className="plus-icon">+</span> 创建项目
          </button>
        </div>
      </div>

      <div className="projects-table">
        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>项目组</th>
              <th>项目</th>
              <th>最新版本</th>
              <th>UAT</th>
              <th>PRO</th>
              <th>更新时间</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan="9" className="loading-cell">加载中...</td>
              </tr>
            ) : projects.length === 0 ? (
              <tr>
                <td colSpan="9" className="no-data-cell">暂无数据</td>
              </tr>
            ) : projects.map((project) => {
              // 查找对应的项目组名称
              const projectGroup = projectGroups.find(group => group.id === project.groupId);
              const groupName = projectGroup ? projectGroup.name : '未知项目组';
              
              return (
                <tr key={project.id}>
                  <td>{project.id}</td>
                  <td>{groupName}</td>
                  <td>{project.name}</td>
                  <td className="version-cell">
                    <a 
                      href="#" 
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        navigate(`/project/${project.id}/versions`);
                      }} 
                      className="version-link"
                    >
                      {project.latestVersion || '暂无版本'}
                    </a>
                  </td>
                  <td>{project.clusterId || '-'}</td>
                  <td>{project.namespaceId || '-'}</td>
                  <td>{project.updatedAt ? new Date(project.updatedAt).toLocaleString() : '-'}</td>
                  <td>{project.createdAt ? new Date(project.createdAt).toLocaleString() : '-'}</td>
                  <td className="actions-cell">
                    <button 
                      type="button" 
                      className="action-button"
                      onClick={(e) => handleAddVersion(e, project)}
                    >
                      新增版本
                    </button>
                    <span className="action-separator">|</span>
                    <a href="#" className="action-link">更多</a>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      
      {/* 创建项目组弹框 */}
      <CreateProjectGroupModal 
        isOpen={isProjectGroupModalOpen}
        onClose={() => setIsProjectGroupModalOpen(false)}
        onSubmit={handleCreateProjectGroup}
      />
      
      {/* 创建项目弹框 */}
      <CreateProjectModal 
        isOpen={isProjectModalOpen}
        onClose={() => setIsProjectModalOpen(false)}
        onSubmit={handleCreateProject}
        projectGroups={projectGroups}
      />
    </div>
  );
};

export default ProjectsPage;
